/**
 * Created by apple on 2017/6/8.
 */
var DBFactory = require('../db/mysql_db');
var async = require('async');
var appAdminDao = module.exports;


appAdminDao.addApp = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            function (callback) {
                connection.query("select sid from apps where sid = ? limit 1",[data.sid],function (err,result) {
                    var sid = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, sid);
                });
            },

            function (sid,callback) {
                if(sid) {//已经该app
                    callback('该app_sid已存在!');
                }else {
                    connection.query('insert into apps set ?',[data],function (err,result) {
                        callback(err,result);
                    });
                }
            },

            function (result,callback) {
                if(result.affectedRows > 0) {

                    var appAgentInfo = {
                        app_sid: data.sid,
                        lvl: 0,
                        name: '普通用户',
                        score: 0,
                    };
                    connection.query('insert into app_agent set ? ',[appAgentInfo],function (err,result) {
                        if(err){
                            callback(err);
                            return;
                        }
                        if(result.affectedRows > 0){
                            callback(null,'操作成功');
                            return;
                        }
                        callback('添加失败');
                        console.log('创建应用时添加代理失败')
                    });

                }else {
                    callback('添加失败');
                    console.log('创建应用添加失败')
                }
            },


        ],function (err,appInfo) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, appInfo);
                    }
                });
            }
        });

    });
}


appAdminDao.updateApp = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }

    var account = data.account;
    var adm_uid = data.adm_uid;
    delete data.account;
    delete data.adm_uid;
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function(err) {
                    callback(err);
                });
            },

            //先查该产品的原参数
            function (callback) {
                connection.query('select * from apps where sid = ? limit 1',[data.sid],function (err,result) {
                    var appInfo = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, appInfo);
                });
            },

            //判断是否存在，存在修改
            function (appInfo,callback) {
                if(!appInfo) {
                    callback('该agent不存在!',null);
                    return;
                }
                connection.query('update apps set ? where sid = ? ',[data,data.sid],function (err,result) {
                    if(err){
                        callback(err,null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,appInfo);
                        return;
                    }
                    callback('操作失败',null);
                    console.log('修改产品时更改apps表失败');
                });
            },

            //修改成功，插入admin_log记录
            function (agentInfo,callback) {
                if(!agentInfo) {
                    callback('操作失败',null);
                    return;
                }

                var adminInfo = {
                    account: account,
                    adm_uid: adm_uid,
                    type: 5,
                    detail: '产品变更：'
                };

                delete data.sid;

                //记录修改的参数
                for(var p in data){
                    adminInfo.detail += p + ':' + agentInfo[p] + '->' + data[p] + ',';
                }

                connection.query('insert into admin_log set ? ',adminInfo,function (err,result) {
                    if(err){
                        callback(err,null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'操作成功');
                        return;
                    }
                    callback('操作失败',null);
                    console.log('更改产品时操作admin_log表失败')

                });
            }

        ],function (err,res) {
            if(err){
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            }else {
                connection.commit(function (e) {
                    if(e){
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });
}


appAdminDao.appList = function (data,cb) {

    var sql;
    var value = [];
    if(data){
        if(data.app_sid){
            sql = 'SELECT sid,name,secret,created_time,icon,comment,adm_account,user_count,mng_items,vip_items,agent_items FROM apps WHERE sid = ? '
            value.push(data.app_sid);
        }else {
            sql = 'SELECT sid,name,secret,created_time,icon,comment,adm_account,user_count,mng_items,vip_items,agent_items FROM apps';
        }
    }else {
        sql = 'SELECT sid,name FROM apps';
    }


    DBFactory.poolQuery(sql, value,
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            cb(null,result);
        }
    );
}



appAdminDao.appDetail = function(data, cb) {
    if(!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.query("select sid,name,secret,icon,comment,adm_account from apps where sid = ? limit 1",[data.app_sid],function (err,result) {
                    var appInfo = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, appInfo);
                });
            },

            function (appInfo,callback) {
                if(!appInfo) {
                    callback(null,'该app不存在!');
                    return;
                }
                //继续查管理项目列表
                connection.query("select sid,name from app_privilege where app_sid = ?",[data.app_sid],function (err,result) {
                    var priList = (result && result.length > 0) ? result : undefined;
                    appInfo.priList = priList;
                    callback(err, appInfo);
                });
            },

            function (appInfo,callback) {
                //继续查VIP项目列表
                connection.query("select sid,name from app_vip where app_sid = ?",[data.app_sid],function (err,result) {
                    var vipList = (result && result.length > 0) ? result : undefined;
                    appInfo.vipList = vipList;
                    callback(err, appInfo);
                });
            }

        ],function (err,appInfo) {
            connection.release();
            if(err){
                cb(err);
                return;
            }
            cb(null,appInfo);

        });

    });
}



appAdminDao.findUsers = function (data,cb) {

    DBFactory.poolQuery('select uid,score,from user_app_new_agent where app_sid = ? ', [data.app_sid],
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            cb(null,result);
        }
    );
}


appAdminDao.getAppKeysAndSecrets = function (data,cb) {

    DBFactory.poolQuery('select sid,secret from apps ',[],
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            cb(null,result);
        }
    );
}